import React, { useState, useEffect, useRef } from 'react';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { llmApi, LLMModel, CreateModelRequest, Conversation, ChatMessage, LLMProvider, TokenUsageResponse } from '../../services/llmApi';
import CustomCard from '../../components/custom/CustomCard';
import CustomButton from '../../components/custom/CustomButton';
import CustomSelect from '../../components/custom/CustomSelect';
import CustomTag from '../../components/custom/CustomTag';
import CustomAlert from '../../components/custom/CustomAlert';
import CustomSpin from '../../components/custom/CustomSpin';
import { 
  FaLightbulb, FaEdit, FaSearch, FaBullseye, 
  FaBook, FaSync, FaTrash, FaCheck, FaPause,
  FaThermometerHalf, FaUser, FaRobot,
  FaComment, FaCalendar, FaGlobe, FaFirefox,
  FaWater, FaUtensilSpoon, FaWaveSquare,
  FaDownload, FaCog, FaRocket, FaStar
} from 'react-icons/fa';

const AIModelManager: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [models, setModels] = useState<LLMModel[]>([]);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedModel, setSelectedModel] = useState<LLMModel | null>(null);
  const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [loading, setLoading] = useState({ 
    models: true, 
    conversations: true, 
    messages: false, 
    send: false,
    providers: true
  });
  const [inputMessage, setInputMessage] = useState('');
  const [isModelModalVisible, setIsModelModalVisible] = useState(false);
  const [isStreaming, setIsStreaming] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [providers, setProviders] = useState<LLMProvider[]>([]);
  
  const [quickPrompts] = useState([
    { icon: <FaLightbulb className="text-yellow-500 animate-pulse" />, text: '解释一下这个概念' },
    { icon: <FaEdit className="text-blue-500 hover:rotate-12 transition-transform duration-300" />, text: '帮我写一份...' },
    { icon: <FaSearch className="text-green-500 hover:scale-110 transition-transform duration-300" />, text: '分析这个问题' },
    { icon: <FaBullseye className="text-red-500 hover:rotate-12 transition-transform duration-300" />, text: '给我一些建议' }
  ]);
  
  const [formData, setFormData] = useState({
    name: '',
    provider: '',
    llm_model_id: '',
    api_key: '',
    base_url: '',
    max_tokens: 4000,
    temperature: 0.7,
    is_active: true
  });
  
  const [showSuccessToast, setShowSuccessToast] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messageInputRef = useRef<HTMLTextAreaElement>(null);

  // 获取提供商列表
  const fetchProviders = async () => {
    try {
      setLoading(prev => ({ ...prev, providers: true }));
      const data = await llmApi.getProviders();
      setProviders(data);
    } catch (error) {
      console.error('获取提供商失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, providers: false }));
    }
  };

  // 获取模型列表
  const fetchModels = async () => {
    try {
      setLoading(prev => ({ ...prev, models: true }));
      const data = await llmApi.getModels();
      setModels(data);
      if (!selectedModel && data.length > 0) {
        setSelectedModel(data[0]);
      }
    } catch (error) {
      console.error('获取模型失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, models: false }));
    }
  };

  // 获取对话列表
  const fetchConversations = async () => {
    try {
      setLoading(prev => ({ ...prev, conversations: true }));
      const data = await llmApi.getConversations(0, 20);
      setConversations(data);
    } catch (error) {
      console.error('获取对话失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, conversations: false }));
    }
  };

  // 获取对话历史
  const fetchConversationHistory = async (conversationId: number) => {
    try {
      setLoading(prev => ({ ...prev, messages: true }));
      const data = await llmApi.getConversationHistory(conversationId);
      setMessages(data.messages);
      setSelectedConversation(data.conversation);
    } catch (error) {
      console.error('获取对话历史失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, messages: false }));
    }
  };

  // 创建新对话
  const createNewConversation = async (modelId: number) => {
    try {
      const newConversation = await llmApi.createConversation({
        title: "新的对话",
        llm_model_id: modelId
      });
      
      setConversations(prev => [newConversation, ...prev]);
      setSelectedConversation(newConversation);
      setMessages([]);
      setShowSuccessToast(true);
      setTimeout(() => setShowSuccessToast(false), 2000);
      return newConversation.id;
    } catch (error) {
      console.error('创建对话失败:', error);
      return 0;
    }
  };

  // 生成对话标题
  const generateConversationTitle = async (conversationId: number, firstMessage: string) => {
    try {
      // 调用AI模型生成标题
      const titleResponse = await llmApi.sendMessage({
        conversation_id: conversationId,
        message: `请为以下对话内容生成一个简洁的标题（不超过15个字）：\n\n用户：${firstMessage}`
      });
      
      // 更新对话标题
      await llmApi.updateConversationTitle(conversationId, titleResponse.message);
      
      // 更新本地状态
      setConversations(prev => prev.map(conv => 
        conv.id === conversationId ? {...conv, title: titleResponse.message} : conv
      ));
      
      if (selectedConversation?.id === conversationId) {
        setSelectedConversation(prev => prev ? {...prev, title: titleResponse.message} : null);
      }
    } catch (error) {
      console.error('生成对话标题失败:', error);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputMessage.trim() || !selectedModel) return;

    try {
      setLoading(prev => ({ ...prev, send: true }));
      setIsStreaming(true);
      
      let conversationId = selectedConversation?.id;
      
      if (!conversationId) {
        const newId = await createNewConversation(selectedModel.id);
        if (!newId) return;
        conversationId = newId;
      }

      const userMessage: ChatMessage = {
        id: Date.now(),
        conversation_id: conversationId,
        role: 'user',
        content: inputMessage,
        created_at: new Date().toISOString()
      };
      
      setMessages(prev => [...prev, userMessage]);
      setInputMessage('');
      
      const response = await llmApi.sendMessage({
        conversation_id: conversationId,
        message: inputMessage
      });
      
      const aiMessage: ChatMessage = {
        id: response.message_id,
        conversation_id: conversationId,
        role: 'assistant',
        content: response.message,
        created_at: new Date().toISOString()
      };
      
      setMessages(prev => [...prev, aiMessage]);
      
      // 如果这是第一条消息，则生成对话标题
      if (messages.length === 0) {
        await generateConversationTitle(conversationId, inputMessage);
      }
      
      fetchConversations();
    } catch (error) {
      console.error('发送消息失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, send: false }));
      setIsStreaming(false);
    }
  };

  // 删除对话
  const deleteConversation = async (conversationId: number) => {
    if (!window.confirm('确定要删除这个对话吗？此操作不可撤销。')) {
      return;
    }
    
    try {
      await llmApi.deleteConversation(conversationId);
      setConversations(prev => prev.filter(c => c.id !== conversationId));
      
      if (selectedConversation?.id === conversationId) {
        setSelectedConversation(null);
        setMessages([]);
      }
    } catch (error) {
      console.error('删除对话失败:', error);
    }
  };

  // 处理模型选择
  const handleModelSelect = (model: LLMModel) => {
    setSelectedModel(model);
  };

  // 处理对话选择
  const handleConversationSelect = (conversation: Conversation) => {
    setSelectedConversation(conversation);
    fetchConversationHistory(conversation.id);
  };

  // 使用快捷提示
  const useQuickPrompt = (text: string) => {
    setInputMessage(text);
    messageInputRef.current?.focus();
  };

  // 提交模型表单
  const handleModelSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const modelData: CreateModelRequest = {
        name: formData.name,
        provider: formData.provider,
        llm_model_id: formData.llm_model_id,
        api_key: formData.api_key || undefined,
        base_url: formData.base_url || undefined,
        max_tokens: formData.max_tokens || undefined,
        temperature: formData.temperature || undefined,
        is_active: formData.is_active
      };
      
      await llmApi.createModel(modelData);
      setIsModelModalVisible(false);
      setFormData({
        name: '',
        provider: '',
        llm_model_id: '',
        api_key: '',
        base_url: '',
        max_tokens: 4000,
        temperature: 0.7,
        is_active: true
      });
      fetchModels();
      
      setShowSuccessToast(true);
      setTimeout(() => setShowSuccessToast(false), 2000);
    } catch (error) {
      console.error('创建模型失败:', error);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchProviders();
    fetchModels();
    fetchConversations();
  }, []);

  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 自动聚焦输入框
  useEffect(() => {
    if (selectedConversation && messageInputRef.current) {
      messageInputRef.current.focus();
    }
  }, [selectedConversation]);

  // 过滤对话
  const filteredConversations = conversations.filter(conv => 
    conv.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    conv.llm_model_name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 可用的提供商列表
  const providerOptions: Array<{value: string, label: string, icon?: React.ReactNode}> = 
    providers.map(provider => ({
      value: provider.provider,
      label: provider.name,
      icon: <FaGlobe className="text-blue-500 hover:text-blue-600 transition-colors" />
    }));

  return (
    <div 
      className="p-4 md:p-6 min-h-screen"
      style={{ 
        backgroundColor: theme.contentBackground,
        color: theme.textPrimary,
        transition: 'background-color 0.3s ease'
      }}
    >
      {/* 顶部标题区域 - 优化视觉效果 */}
      <div className="mb-6 animate-fade-in">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div>
            <h1 
              className="text-3xl md:text-4xl font-extrabold mb-2 tracking-tight"
              style={{ 
                background: mode === 'dark' 
                  ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' 
                  : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text'
              }}
            >
              AI 模型管理中心
            </h1>
            <p 
              className="text-base md:text-lg max-w-2xl"
              style={{ 
                color: theme.textSecondary
              }}
            >
              配置和管理您的AI模型，与智能助手进行深度对话
            </p>
          </div>
          <div className="flex gap-2 flex-wrap">
            <CustomButton
              type="primary"
              onClick={() => window.location.href = '/api/docs'}
              className="px-3 py-2 md:px-4 md:py-2 rounded-lg transition-all duration-300 hover:scale-105 text-white flex items-center gap-2 text-sm md:text-base"
            >
              <FaBook className="text-blue-500" /> API文档
            </CustomButton>
            <CustomButton
              type="default"
              onClick={() => fetchModels()}
              className="px-3 py-2 md:px-4 md:py-2 rounded-lg transition-all duration-300 hover:scale-105 flex items-center gap-2 text-sm md:text-base"
            >
              <FaSync className="text-green-500 hover:rotate-180 transition-transform duration-500" /> 刷新
            </CustomButton>
          </div>
        </div>
      </div>

      {/* 主内容区 - 优化响应式布局 */}
      <div className="flex flex-col lg:flex-row gap-4 md:gap-6 min-h-[calc(100vh-200px)]">
        {/* 左侧：模型和对话列表 */}
        <div className="w-full lg:w-1/3 xl:w-1/3 2xl:w-1/4 flex flex-col gap-4 md:gap-6">
          {/* 提供商状态面板 */}
          <CustomCard className="flex flex-col shadow-xl hover:shadow-2xl transition-all duration-300">
            <div className="border-b pb-3 md:pb-4 mb-3 md:mb-4 px-3 md:px-4" style={{ borderColor: theme.borderColor }}>
              <div className="flex justify-between items-center">
                <span className="font-bold text-lg flex items-center gap-2"><FaGlobe className="text-blue-500" /> 提供商状态</span>
                <CustomButton 
                  type="secondary"
                  size="small"
                  onClick={() => fetchProviders()}
                  className="transform hover:scale-105 transition-transform"
                >
                  <FaSync className="text-blue-500 hover:rotate-180 transition-transform duration-500" />
                </CustomButton>
              </div>
            </div>
            
            <div className="flex-1 overflow-y-auto overflow-x-hidden p-1 min-h-0">
              {loading.providers ? (
                <div className="text-center py-4">
                  <CustomSpin size="small" />
                  <p className="mt-2" style={{ color: theme.textSecondary }}>加载提供商中...</p>
                </div>
              ) : providers.length === 0 ? (
                <div className="text-center py-4">
                  <div className="text-2xl mb-2 flex justify-center"><FaSearch className="text-blue-400" /></div>
                  <p style={{ color: theme.textSecondary }}>暂无提供商信息</p>
                </div>
              ) : (
                <div className="space-y-3 px-2">
                  {providers.map(provider => (
                    <div
                      key={provider.provider}
                      className="group cursor-pointer transition-all duration-300 rounded-lg md:rounded-xl p-3 md:p-4 relative overflow-hidden"
                      style={{
                        background: mode === 'dark' ? 'rgba(255, 255, 255, 0.03)' : 'rgba(0, 0, 0, 0.02)',
                        border: `1px solid ${theme.borderColor}`,
                      }}
                    >
                      <div className="flex justify-between items-center mb-2">
                        <div className="flex items-center gap-2">
                          <span className="text-base font-bold">{provider.name}</span>
                          {provider.is_available ? (
                            <span className="text-xs text-green-500"><FaCheck /></span>
                          ) : (
                            <span className="text-xs text-red-500"><FaPause /></span>
                          )}
                        </div>
                        <span 
                          className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                            provider.is_available 
                              ? (mode === 'dark' 
                                  ? 'bg-[rgba(97,220,163,0.2)] text-[#61dca3] border border-[rgba(97,220,163,0.3)]' 
                                  : 'bg-[rgba(97,220,163,0.1)] text-[#61dca3] border border-[rgba(97,220,163,0.2)]')
                              : (mode === 'dark' 
                                  ? 'bg-[rgba(255,255,255,0.1)] border border-gray-700' 
                                  : 'bg-[rgba(0,0,0,0.05)] border border-gray-200')
                          }`}
                          style={{
                            fontSize: '10px',
                            fontWeight: 600,
                            borderRadius: '12px'
                          }}
                        >
                          {provider.is_available ? '可用' : '不可用'}
                        </span>
                      </div>
                      
                      <div className="space-y-1 text-xs" style={{ color: theme.textSecondary }}>
                        <div className="flex items-center gap-1">
                          <span className="font-mono text-xs">{provider.provider}</span>
                        </div>
                        <div className="flex flex-wrap gap-1 mt-2">
                          {provider.models.slice(0, 3).map((model, idx) => (
                            <span 
                              key={idx}
                              className="inline-block px-2 py-1 rounded-full"
                              style={{ 
                                background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                                fontSize: '10px'
                              }}
                            >
                              {model}
                            </span>
                          ))}
                          {provider.models.length > 3 && (
                            <span 
                              className="inline-block px-2 py-1 rounded-full"
                              style={{ 
                                background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                                fontSize: '10px'
                              }}
                            >
                              +{provider.models.length - 3} 更多
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </CustomCard>

          {/* 模型列表卡片 */}
          <CustomCard className="flex-1 flex flex-col shadow-xl hover:shadow-2xl transition-all duration-300 min-h-0">
            <div className="border-b pb-3 md:pb-4 mb-3 md:mb-4 px-3 md:px-4" style={{ borderColor: theme.borderColor }}>
              <div className="flex justify-between items-center">
                <span className="font-bold text-lg flex items-center gap-2"><FaRobot className="text-purple-500" /> 模型列表</span>
                <div className="flex gap-2">
                  <CustomButton 
                    type="secondary"
                    size="small"
                    onClick={async () => {
                      try {
                        await llmApi.autoCreateModelsFromEnv();
                        fetchModels();
                        setShowSuccessToast(true);
                        setTimeout(() => setShowSuccessToast(false), 2000);
                      } catch (error) {
                        console.error('自动创建模型失败:', error);
                      }
                    }}
                    className="transform hover:scale-105 transition-transform"
                  >
                    自动创建
                  </CustomButton>
                  <CustomButton 
                    type="primary"
                    size="small"
                    onClick={() => setIsModelModalVisible(true)}
                    className="transform hover:scale-105 transition-transform"
                  >
                    + 添加
                  </CustomButton>
                </div>
              </div>
            </div>
            
            <div className="flex-1 overflow-y-auto overflow-x-hidden p-1 min-h-0">
              {loading.models ? (
                <div className="text-center py-8 md:py-10">
                  <CustomSpin size="large" />
                  <p className="mt-3" style={{ color: theme.textSecondary }}>加载模型中...</p>
                </div>
              ) : models.length === 0 ? (
                <div className="text-center py-8 md:py-12">
                  <div className="text-4xl md:text-5xl mb-3 md:mb-4 flex justify-center"><FaSearch className="text-blue-400" /></div>
                  <p style={{ color: theme.textSecondary, marginBottom: '0.75rem' }}>暂无可用模型</p>
                  <CustomButton
                    type="primary"
                    onClick={() => setIsModelModalVisible(true)}
                    className="px-3 py-2 md:px-4 md:py-2 rounded-lg text-white transition-all duration-300 hover:scale-105 text-sm md:text-base"
                  >
                    添加模型
                  </CustomButton>
                </div>
              ) : (
                <div className="space-y-3 px-2">
                  {models.map(model => (
                    <div
                      key={model.id}
                      className={`group cursor-pointer transition-all duration-300 rounded-lg md:rounded-xl p-3 md:p-4 relative overflow-hidden ${
                        selectedModel?.id === model.id ? 'scale-[1.02]' : 'hover:scale-[1.01]'
                      }`}
                      style={{
                        background: selectedModel?.id === model.id 
                          ? `linear-gradient(135deg, ${mode === 'dark' ? 'rgba(102, 126, 234, 0.2)' : 'rgba(102, 126, 234, 0.1)'}, ${mode === 'dark' ? 'rgba(118, 75, 162, 0.2)' : 'rgba(118, 75, 162, 0.1)'})` 
                          : (mode === 'dark' ? 'rgba(255, 255, 255, 0.03)' : 'rgba(0, 0, 0, 0.02)'),
                        border: `1px solid ${selectedModel?.id === model.id 
                          ? (mode === 'dark' ? 'rgba(102, 126, 234, 0.5)' : 'rgba(102, 126, 234, 0.3)')
                          : theme.borderColor}`,
                        boxShadow: selectedModel?.id === model.id 
                          ? '0 8px 20px rgba(102, 126, 234, 0.2)' 
                          : 'none'
                      }}
                      onClick={() => handleModelSelect(model)}
                    >
                      <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500"
                        style={{
                          background: `radial-gradient(circle at 20% 50%, ${mode === 'dark' ? 'rgba(102, 126, 234, 0.15)' : 'rgba(102, 126, 234, 0.08)'} 0%, transparent 60%)`
                        }} />
                      
                      <div className="relative z-10">
                        <div className="flex justify-between items-start mb-2">
                          <div className="flex items-center gap-2">
                            <span className="text-base md:text-lg font-bold truncate max-w-[70%]">{model.name}</span>
                            {selectedModel?.id === model.id && (
                              <span className="text-sm text-green-500 animate-bounce"><FaCheck /></span>
                            )}
                          </div>
                          <span 
                            className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium whitespace-nowrap ${
                              model.is_active 
                                ? (mode === 'dark' 
                                    ? 'bg-[rgba(97,220,163,0.2)] text-[#61dca3] border border-[rgba(97,220,163,0.3)]' 
                                    : 'bg-[rgba(97,220,163,0.1)] text-[#61dca3] border border-[rgba(97,220,163,0.2)]')
                                : (mode === 'dark' 
                                    ? 'bg-[rgba(255,255,255,0.1)] border border-gray-700' 
                                    : 'bg-[rgba(0,0,0,0.05)] border border-gray-200')
                            }`}
                            style={{
                              fontSize: '11px',
                              fontWeight: 600,
                              borderRadius: '12px'
                            }}
                          >
                            {model.is_active ? <><FaCheck className="text-green-500" /> 启用</> : <><FaPause className="text-yellow-500" /> 禁用</>}
                          </span>
                        </div>
                        
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 text-xs md:text-sm" style={{ color: theme.textSecondary }}>
                            <span className="flex items-center gap-1">
                              <FaGlobe className="text-blue-400" /> 
                              {model.provider}
                              {providers.find(p => p.provider === model.provider)?.name && 
                                ` (${providers.find(p => p.provider === model.provider)?.name})`}
                            </span>
                            <span>•</span>
                            <span className="font-mono text-xs">{model.llm_model_id}</span>
                          </div>
                        
                          <div className="flex flex-wrap gap-2">
                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] md:text-[11px] font-medium" 
                              style={{ 
                                background: 'linear-gradient(135deg, rgba(79, 172, 254, 0.2), rgba(0, 242, 254, 0.2))',
                                color: mode === 'dark' ? '#4facfe' : '#0084ff'
                              }}>
                              <FaBullseye className="text-purple-500" /> Tokens: {model.max_tokens}
                            </span>
                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] md:text-[11px] font-medium"
                              style={{ 
                                background: 'linear-gradient(135deg, rgba(240, 147, 251, 0.2), rgba(245, 87, 108, 0.2))',
                                color: mode === 'dark' ? '#f093fb' : '#f5576c'
                              }}>
                              <FaThermometerHalf className="text-red-500" /> Temp: {model.temperature}
                            </span>
                            {providers.find(p => p.provider === model.provider)?.is_available ? (
                              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] md:text-[11px] font-medium"
                                style={{ 
                                  background: 'linear-gradient(135deg, rgba(97, 220, 163, 0.2), rgba(76, 175, 80, 0.2))',
                                  color: mode === 'dark' ? '#61dca3' : '#4caf50'
                                }}>
                                <FaCheck className="text-green-500" /> 可用
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] md:text-[11px] font-medium"
                                style={{ 
                                  background: 'linear-gradient(135deg, rgba(255, 152, 0, 0.2), rgba(255, 167, 38, 0.2))',
                                  color: mode === 'dark' ? '#ff9800' : '#ffa726'
                                }}>
                                <FaPause className="text-orange-500" /> 不可用
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </CustomCard>

          {/* 对话列表卡片 */}
          <div className="flex-1 flex flex-col shadow-xl hover:shadow-2xl transition-all duration-300 rounded-lg p-4 md:p-6 backdrop-blur-md min-h-0"
            style={{
              background: mode === 'dark' 
                ? 'linear-gradient(145deg, rgba(255,255,255,0.05), rgba(255,255,255,0.02))'
                : 'linear-gradient(145deg, rgba(255,255,255,0.95), rgba(255,255,255,0.85))',
              border: `1px solid ${mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)'}`,
              backdropFilter: 'blur(10px)'
            }}>
            <div className="border-b pb-3 md:pb-4 mb-3 md:mb-4 px-2 md:px-4" style={{ borderColor: theme.borderColor }}>
              <div className="flex justify-between items-center mb-3">
                <span className="font-bold text-lg flex items-center gap-2"><FaComment /> 对话列表</span>
                <div className="flex gap-2">
                  <CustomButton
                    type="secondary"
                    size="small"
                    onClick={() => fetchConversations()}
                    className="transition-all duration-300 hover:scale-105"
                  >
                    <FaSync className="text-blue-500 hover:rotate-180 transition-transform duration-500" />
                  </CustomButton>
                  <CustomButton
                    type="primary"
                    size="small"
                    disabled={!selectedModel}
                    onClick={() => selectedModel && createNewConversation(selectedModel.id)}
                    className={`transition-all duration-300 hover:scale-105 flex items-center gap-1 ${
                      !selectedModel ? 'opacity-50 cursor-not-allowed' : ''
                    }`}
                  >
                    <FaComment className="text-white" /> + 新对话
                  </CustomButton>
                </div>
              </div>
              
              {/* 搜索框 */}
              <div className="relative">
                <input
                  type="text"
                  placeholder="搜索对话..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full px-3 py-2 pl-9 rounded-lg text-sm transition-all duration-300 focus:ring-2 focus:outline-none"
                  style={{
                    background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                    border: `1px solid ${theme.borderColor}`,
                    color: theme.textPrimary
                  }}
                />
                <span className="absolute left-3 top-2.5 text-sm text-blue-500"><FaSearch className="text-blue-500" /></span>
              </div>
            </div>
            
            <div className="flex-1 overflow-y-auto overflow-x-hidden p-1 min-h-0">
              {loading.conversations ? (
                <div className="text-center py-8 md:py-10">
                  <CustomSpin size="large" />
                  <p className="mt-3" style={{ color: theme.textSecondary }}>加载对话中...</p>
                </div>
              ) : filteredConversations.length === 0 ? (
                <div className="text-center py-8 md:py-12">
                  <div className="text-4xl md:text-5xl mb-3 md:mb-4">💭</div>
                  <p style={{ color: theme.textSecondary, marginBottom: '0.75rem' }}>
                    {searchQuery ? '未找到匹配的对话' : '暂无对话记录'}
                  </p>
                  {!searchQuery && (
                    <CustomButton
                      type="primary"
                      onClick={() => selectedModel && createNewConversation(selectedModel.id)}
                      disabled={!selectedModel}
                      className={`px-3 py-2 md:px-4 md:py-2 rounded-lg text-white transition-all duration-300 hover:scale-105 text-sm md:text-base ${
                        !selectedModel ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      开始新对话
                    </CustomButton>
                  )}
                </div>
              ) : (
                <div className="space-y-3 px-2">
                  {filteredConversations.map(conversation => (
                    <div
                      key={conversation.id}
                      className={`group cursor-pointer transition-all duration-300 rounded-lg md:rounded-xl p-3 md:p-4 relative overflow-hidden ${
                        selectedConversation?.id === conversation.id ? 'scale-[1.02]' : 'hover:scale-[1.01]'
                      }`}
                      style={{
                        background: selectedConversation?.id === conversation.id 
                          ? `linear-gradient(135deg, ${mode === 'dark' ? 'rgba(240, 147, 251, 0.2)' : 'rgba(240, 147, 251, 0.1)'}, ${mode === 'dark' ? 'rgba(245, 87, 108, 0.2)' : 'rgba(245, 87, 108, 0.1)'})` 
                          : (mode === 'dark' ? 'rgba(255, 255, 255, 0.03)' : 'rgba(0, 0, 0, 0.02)'),
                        border: `1px solid ${selectedConversation?.id === conversation.id 
                          ? (mode === 'dark' ? 'rgba(240, 147, 251, 0.5)' : 'rgba(240, 147, 251, 0.3)')
                          : theme.borderColor}`,
                        boxShadow: selectedConversation?.id === conversation.id 
                          ? '0 8px 20px rgba(240, 147, 251, 0.2)' 
                          : 'none'
                      }}
                      onClick={() => handleConversationSelect(conversation)}
                    >
                      <div className="flex justify-between items-start mb-2">
                        <span className="font-semibold truncate flex-1 mr-2 text-sm md:text-base">{conversation.title}</span>
                        <CustomButton
                          type="default"
                          className="opacity-0 group-hover:opacity-100 transition-all duration-300 p-1 rounded-lg hover:bg-red-500/20 transform hover:scale-110"
                          onClick={() => deleteConversation(conversation.id)}
                          title="删除对话"
                        >
                          <FaTrash className="text-red-500 hover:text-red-600" />
                        </CustomButton>
                      </div>
                      
                      <div className="space-y-1 text-xs" style={{ color: theme.textSecondary }}>
                        <div className="flex items-center gap-2">
                          <span className="flex items-center gap-1"><FaRobot className="text-purple-400" /> {conversation.llm_model_name}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="flex items-center gap-1"><FaCalendar className="text-green-500" /> {new Date(conversation.updated_at).toLocaleDateString()}</span>
                          <span className="flex items-center gap-1"><FaComment className="text-blue-500" /> {conversation.message_count} 条</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 右侧：对话区域 */}
        <div className="w-full lg:w-2/3 xl:w-2/3 2xl:w-3/4 flex flex-col">
          <div className="flex-1 flex flex-col shadow-xl hover:shadow-2xl transition-all duration-300 rounded-lg p-4 md:p-6 backdrop-blur-md min-h-[500px]"
            style={{
              background: mode === 'dark' 
                ? 'linear-gradient(145deg, rgba(255,255,255,0.05), rgba(255,255,255,0.02))'
                : 'linear-gradient(145deg, rgba(255,255,255,0.95), rgba(255,255,255,0.85))',
              border: `1px solid ${mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)'}`,
              backdropFilter: 'blur(10px)'
            }}>
            {selectedConversation ? (
              <>
                <div className="border-b pb-3 md:pb-4 mb-3 md:mb-4 px-2 md:px-4" style={{ borderColor: theme.borderColor }}>
                  <div className="flex justify-between items-center">
                    <div className="max-w-[80%]">
                      <h3 style={{ fontWeight: 700, fontSize: '1.1rem', marginBottom: '0.25rem' }} className="md:text-lg truncate">
                        {selectedConversation.title}
                      </h3>
                      <p style={{ color: theme.textSecondary, fontSize: '0.8rem' }} className="md:text-sm flex items-center gap-1 flex-wrap">
                        <FaRobot className="text-purple-500" /> {selectedConversation.llm_model_name} • <FaGlobe className="text-blue-500" /> {selectedConversation.provider}
                        {providers.find(p => p.provider === selectedConversation.provider)?.is_available === false && (
                          <span className="text-red-500 text-xs flex items-center gap-1">
                            <FaPause /> 不可用
                          </span>
                        )}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <CustomButton
                        type="secondary"
                        size="small"
                        onClick={() => fetchConversationHistory(selectedConversation.id)}
                        className="p-1.5"
                      >
                        <FaSync className="text-blue-500 hover:rotate-180 transition-transform duration-500" />
                      </CustomButton>
                      {isStreaming && (
                        <span className="px-2 py-1 md:px-3 md:py-1 rounded-full text-xs font-medium animate-pulse"
                          style={{
                            background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                            color: '#fff'
                          }}>
                          AI 正在思考...
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* 消息区域 - 优化滚动区域 */}
                <div 
                  className="flex-1 overflow-y-auto p-3 md:p-6 space-y-4 min-h-0"
                  style={{ 
                    background: mode === 'dark' 
                      ? 'linear-gradient(180deg, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0.1) 100%)'
                      : 'linear-gradient(180deg, rgba(0,0,0,0.02) 0%, rgba(0,0,0,0.01) 100%)',
                    scrollBehavior: 'smooth',
                    overscrollBehavior: 'contain'
                  }}
                >
                  {loading.messages ? (
                    <div className="flex flex-col items-center justify-center h-full">
                      <CustomSpin size="large" />
                      <p className="mt-4" style={{ color: theme.textSecondary }}>加载对话历史中...</p>
                    </div>
                  ) : messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full">
                      <div className="text-5xl md:text-6xl mb-3 md:mb-4 flex justify-center text-blue-500 animate-pulse"><FaWaveSquare className="text-blue-500 animate-pulse" /></div>
                      <p style={{ color: theme.textSecondary, fontSize: '1rem', maxWidth: '400px', textAlign: 'center' }} className="md:text-lg">
                        开始与 {selectedConversation.llm_model_name} 对话吧！
                      </p>
                      
                      {/* 快捷提示 */}
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 md:gap-3 mt-4 md:mt-6 w-full max-w-md">
                        {quickPrompts.map((prompt, idx) => (
                          <CustomButton
                            key={idx}
                            onClick={() => useQuickPrompt(prompt.text)}
                            type="default"
                            className="px-3 py-2 md:px-4 md:py-3 rounded-lg md:rounded-xl transition-all duration-300 hover:scale-105 text-xs md:text-sm font-medium text-left"
                            style={{
                              background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                              border: `1px solid ${theme.borderColor}`,
                              color: theme.textPrimary,
                              justifyContent: 'flex-start'
                            }}
                          >
                            <span className="mr-1 md:mr-2 flex-shrink-0">{prompt.icon}</span>
                            <span className="truncate">{prompt.text}</span>
                          </CustomButton>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <>
                      {messages.map((msg, index) => (
                        <div 
                          key={msg.id} 
                          className={`flex animate-fade-in-up ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
                          style={{ animationDelay: `${index * 0.05}s` }}
                        >
                          <div className={`flex gap-2 md:gap-3 max-w-[85%] md:max-w-[80%] ${msg.role === 'user' ? 'flex-row-reverse' : 'flex-row'}`}>
                            <div className="flex-shrink-0">
                              <div 
                                className="w-8 h-8 md:w-10 md:h-10 rounded-full flex items-center justify-center text-lg md:text-xl"
                                style={{
                                  background: msg.role === 'user' 
                                    ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' 
                                    : 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                                  boxShadow: '0 4px 10px rgba(0,0,0,0.1)'
                                }}
                              >
                                {msg.role === 'user' ? <FaUser className="text-white text-xs md:text-base" /> : <FaRobot className="text-white text-xs md:text-base" />}
                              </div>
                            </div>
                            
                            <div 
                              className={`px-4 py-3 md:px-5 md:py-4 rounded-2xl ${
                                msg.role === 'user' ? 'rounded-br-sm' : 'rounded-bl-sm'
                              }`}
                              style={{
                                background: msg.role === 'user' 
                                  ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' 
                                  : (mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.04)'),
                                color: msg.role === 'user' ? '#fff' : theme.textPrimary,
                                boxShadow: msg.role === 'user' 
                                  ? '0 5px 15px rgba(102, 126, 234, 0.3)' 
                                  : '0 3px 10px rgba(0, 0, 0, 0.05)',
                                whiteSpace: 'pre-wrap',
                                wordBreak: 'break-word',
                                fontSize: '0.85rem',
                                lineHeight: '1.5',
                              }}
                            >
                              {msg.content}
                            </div>
                          </div>
                        </div>
                      ))}
                      <div ref={messagesEndRef} />
                      
                      {loading.send && (
                        <div className="flex justify-start animate-pulse">
                          <div className="flex gap-2 md:gap-3 max-w-[85%] md:max-w-[80%]">
                            <div className="w-8 h-8 md:w-10 md:h-10 rounded-full flex items-center justify-center text-lg md:text-xl"
                              style={{
                                background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                                boxShadow: '0 4px 10px rgba(0,0,0,0.1)'
                              }}>
                              <FaRobot className="text-white text-xs md:text-base" />
                            </div>
                            <div className="px-4 py-2 md:px-5 md:py-3 rounded-2xl rounded-bl-sm"
                              style={{
                                background: mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.04)',
                                color: theme.textPrimary
                              }}>
                              <div className="flex space-x-1 md:space-x-2">
                                <div className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-current animate-bounce" style={{ animationDelay: '0ms' }}></div>
                                <div className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-current animate-bounce" style={{ animationDelay: '150ms' }}></div>
                                <div className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-current animate-bounce" style={{ animationDelay: '300ms' }}></div>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
                
                {/* 输入区域 - 优化布局 */}
                <div className="border-t p-3 md:p-4" style={{ borderColor: theme.borderColor }}>
                  {/* 快捷操作栏 */}
                  <div className="flex gap-2 mb-2 md:mb-3">
                    <CustomButton
                      type="default"
                      onClick={() => setMessages([])}
                      title="清空对话"
                      className="p-1.5 md:p-2 rounded-lg transition-all duration-300 hover:scale-110 hover:bg-red-500/20"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textSecondary
                      }}
                    >
                      <FaTrash className="text-red-500 hover:text-red-600 text-sm md:text-base" />
                    </CustomButton>
                    <CustomButton
                      type="default"
                      onClick={async () => {
                        if (selectedConversation) {
                          try {
                            const tokenUsage = await llmApi.getConversationTokens(selectedConversation.id);
                            alert(`Token使用情况:
总Token数: ${tokenUsage.total_tokens}
提示Token: ${tokenUsage.prompt_tokens}
完成Token: ${tokenUsage.completion_tokens}
估算成本: $${tokenUsage.estimated_cost}`);
                          } catch (error) {
                            console.error('获取Token使用情况失败:', error);
                          }
                        }
                      }}
                      title="Token使用情况"
                      className="p-1.5 md:p-2 rounded-lg transition-all duration-300 hover:scale-110 hover:bg-blue-500/20"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textSecondary
                      }}
                      disabled={!selectedConversation}
                    >
                      <FaWaveSquare className="text-blue-500 hover:text-blue-600 text-sm md:text-base" />
                    </CustomButton>
                    <CustomButton
                      type="default"
                      title="导出对话"
                      className="p-1.5 md:p-2 rounded-lg transition-all duration-300 hover:scale-110 hover:bg-green-500/20"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textSecondary
                      }}
                      onClick={() => {
                        if (selectedConversation && messages.length > 0) {
                          const conversationText = `对话标题: ${selectedConversation.title}
模型: ${selectedConversation.llm_model_name}
提供商: ${selectedConversation.provider}

` +
                            messages.map(msg => `${msg.role === 'user' ? '用户' : 'AI'}: ${msg.content}`).join('\n\n');
                          
                          const blob = new Blob([conversationText], { type: 'text/plain' });
                          const url = URL.createObjectURL(blob);
                          const a = document.createElement('a');
                          a.href = url;
                          a.download = `对话_${selectedConversation.title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')}.txt`;
                          document.body.appendChild(a);
                          a.click();
                          document.body.removeChild(a);
                          URL.revokeObjectURL(url);
                        }
                      }}
                      disabled={!selectedConversation || messages.length === 0}
                    >
                      <FaDownload className="text-green-500 hover:text-green-600 text-sm md:text-base" />
                    </CustomButton>
                    <CustomButton
                      type="default"
                      title="设置"
                      className="p-1.5 md:p-2 rounded-lg transition-all duration-300 hover:scale-110 hover:bg-gray-500/20"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textSecondary
                      }}
                    >
                      <FaCog className="text-gray-500 hover:text-gray-600 text-sm md:text-base" />
                    </CustomButton>
                  </div>
                  
                  <textarea
                    ref={messageInputRef}
                    className="w-full mb-2 md:mb-3 rounded-lg md:rounded-xl p-3 md:p-4 font-sans min-h-[80px] md:min-h-[100px] resize-y transition-all duration-300 focus:ring-2 focus:outline-none text-sm md:text-base"
                    value={inputMessage}
                    onChange={(e) => setInputMessage(e.target.value)}
                    placeholder="输入您的消息...按Enter发送，Shift+Enter换行"
                    style={{
                      background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                      border: `1px solid ${theme.borderColor}`,
                      color: theme.textPrimary
                    }}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        sendMessage();
                      }
                    }}
                  />
                  
                  <div className="flex justify-between items-center">
                    <div className="flex items-center gap-2 md:gap-3">
                      <span className="text-xs" style={{ color: theme.textSecondary }}>
                        {inputMessage.length} 字符
                      </span>
                      <span className="text-xs hidden sm:block" style={{ color: theme.textSecondary }}>
                        按Enter发送
                      </span>
                    </div>
                    <CustomButton
                      type="primary"
                      onClick={sendMessage}
                      disabled={!inputMessage.trim() || loading.send || !selectedModel}
                      loading={loading.send}
                      className={`transform hover:scale-105 transition-all text-sm md:text-base px-3 py-1.5 md:px-4 md:py-2 ${(!inputMessage.trim() || loading.send || !selectedModel) ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      <span className="flex items-center gap-1 md:gap-2">
                        <span>发送</span>
                        <FaRocket className="animate-bounce text-sm" />
                      </span>
                    </CustomButton>
                  </div>
                </div>
              </>
            ) : (
              <div className="flex-1 flex flex-col justify-center items-center p-4 md:p-8">
                <div className="text-6xl md:text-7xl mb-4 md:mb-6 animate-bounce-slow flex justify-center text-blue-500"><FaComment className="text-blue-500" /></div>
                <h3 style={{ 
                  fontSize: '1.25rem', 
                  fontWeight: 700, 
                  marginBottom: '0.75rem',
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                  backgroundClip: 'text'
                }} className="md:text-2xl">
                  开始智能对话
                </h3>
                <p style={{ 
                  color: theme.textSecondary, 
                  fontSize: '0.9rem', 
                  maxWidth: '400px', 
                  textAlign: 'center',
                  marginBottom: '1.5rem'
                }} className="md:text-lg">
                  选择一个模型并创建新对话，或从左侧选择现有对话继续
                </p>
                
                {selectedModel && (
                  <CustomButton 
                    type="primary"
                    size="large"
                    onClick={() => createNewConversation(selectedModel.id)}
                    className="transform hover:scale-105 transition-all px-6 py-2 md:px-8 md:py-3 text-base md:text-lg"
                  >
                    <span className="flex items-center gap-2">
                      <span>与 {selectedModel.name} 开始对话</span>
                      <FaStar className="text-yellow-300 animate-pulse" />
                    </span>
                  </CustomButton>
                )}
                
                {!selectedModel && (
                  <div className="text-center">
                    <p style={{ color: theme.textSecondary, marginBottom: '0.75rem' }} className="md:text-lg">
                      请先从左侧选择一个模型
                    </p>
                    {models.length === 0 && (
                      <CustomButton 
                        type="primary"
                        onClick={() => setIsModelModalVisible(true)}
                        className="px-4 py-2 md:px-6 md:py-3 text-sm md:text-base"
                      >
                        添加第一个模型
                      </CustomButton>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 添加模型模态框 - 优化设计 */}
      {isModelModalVisible && (
        <div
          className="fixed inset-0 bg-black/60 backdrop-blur-sm flex justify-center items-center z-[1000] animate-fade-in"
          onClick={() => setIsModelModalVisible(false)}
        >
          <div
            className="rounded-2xl w-[95%] sm:w-[90%] md:w-[70%] lg:w-[60%] xl:w-[50%] max-w-2xl max-h-[90vh] overflow-y-auto relative animate-scale-in shadow-2xl"
            style={{
              background: mode === 'dark' 
                ? 'linear-gradient(145deg, #1a1a1a, #2d2d2d)' 
                : 'linear-gradient(145deg, #ffffff, #f5f5f5)',
              border: `1px solid ${theme.cardBorder}`,
              animation: 'slideUp 0.3s ease-out'
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="border-b px-6 py-5 flex justify-between items-center"
              style={{ borderColor: theme.borderColor }}>
              <h2 style={{ 
                fontSize: '1.5rem', 
                fontWeight: 700,
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text'
              }}>
                添加新模型
              </h2>
              <CustomButton
                type="default"
                className="w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110"
                style={{ 
                  background: mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)',
                  color: theme.textSecondary
                }}
                onClick={() => setIsModelModalVisible(false)}
              >
                ✕
              </CustomButton>
            </div>
            
            <div className="p-6">
              <form onSubmit={handleModelSubmit}>
                <div className="space-y-5">
                  <div>
                    <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                      模型名称 <span style={{ color: '#ff4d4f' }}>*</span>
                    </label>
                    <input
                      type="text"
                      className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textPrimary
                      }}
                      value={formData.name}
                      onChange={(e) => setFormData({...formData, name: e.target.value})}
                      placeholder="例如：GPT-4 Turbo"
                      required
                    />
                  </div>
                  
                  <div>
                    <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                      提供商 <span style={{ color: '#ff4d4f' }}>*</span>
                    </label>
                    <CustomSelect
                      value={formData.provider}
                      onChange={(value) => setFormData({...formData, provider: value})}
                      options={providerOptions}
                      placeholder="选择提供商"
                      loading={loading.providers}
                    />
                    {providers.length > 0 && (
                      <div className="mt-2 text-xs" style={{ color: theme.textSecondary }}>
                        <span>可用提供商: </span>
                        {providers.filter(p => p.is_available).map((provider, idx) => (
                          <span key={provider.provider} className="mr-2">
                            {provider.name}{idx < providers.filter(p => p.is_available).length - 1 ? ',' : ''}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  
                  <div>
                    <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                      模型ID <span style={{ color: '#ff4d4f' }}>*</span>
                    </label>
                    <input
                      type="text"
                      className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textPrimary
                      }}
                      value={formData.llm_model_id}
                      onChange={(e) => setFormData({...formData, llm_model_id: e.target.value})}
                      placeholder="例如：gpt-4-turbo"
                      required
                    />
                    {formData.provider && providers.find(p => p.provider === formData.provider)?.models && (
                      <div className="mt-2">
                        <div className="text-xs mb-1" style={{ color: theme.textSecondary }}>
                          推荐模型:
                        </div>
                        <div className="flex flex-wrap gap-1">
                          {providers.find(p => p.provider === formData.provider)?.models.slice(0, 3).map((model, idx) => (
                            <CustomButton
                              key={idx}
                              type="secondary"
                              size="tiny"
                              onClick={() => setFormData({...formData, llm_model_id: model})}
                              className="text-xs"
                            >
                              {model}
                            </CustomButton>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                  
                  <div>
                    <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                      API Key
                    </label>
                    <input
                      type="password"
                      className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textPrimary
                      }}
                      value={formData.api_key}
                      onChange={(e) => setFormData({...formData, api_key: e.target.value})}
                      placeholder="可选，留空使用环境变量"
                    />
                    <div className="mt-1 text-xs" style={{ color: theme.textSecondary }}>
                      如果留空，系统将尝试从环境变量中获取API密钥
                    </div>
                  </div>
                  
                  <div>
                    <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                      Base URL
                    </label>
                    <input
                      type="text"
                      className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                      style={{
                        background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                        border: `1px solid ${theme.borderColor}`,
                        color: theme.textPrimary
                      }}
                      value={formData.base_url}
                      onChange={(e) => setFormData({...formData, base_url: e.target.value})}
                      placeholder="可选，默认值将根据提供商自动设置"
                    />
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                        Max Tokens
                      </label>
                      <input
                        type="number"
                        className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                        style={{
                          background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                          border: `1px solid ${theme.borderColor}`,
                          color: theme.textPrimary
                        }}
                        value={formData.max_tokens}
                        onChange={(e) => setFormData({...formData, max_tokens: parseInt(e.target.value) || 4000})}
                        min="1"
                        max="128000"
                      />
                    </div>
                    
                    <div>
                      <label className="block mb-2 font-semibold" style={{ color: theme.textPrimary }}>
                        Temperature
                      </label>
                      <input
                        type="number"
                        step="0.1"
                        min="0"
                        max="2"
                        className="w-full p-3 rounded-xl transition-all duration-300 focus:ring-2 focus:outline-none"
                        style={{
                          background: mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)',
                          border: `1px solid ${theme.borderColor}`,
                          color: theme.textPrimary
                        }}
                        value={formData.temperature}
                        onChange={(e) => setFormData({...formData, temperature: parseFloat(e.target.value) || 0.7})}
                      />
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-3 pt-2">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        className="sr-only peer"
                        checked={formData.is_active}
                        onChange={(e) => setFormData({...formData, is_active: e.target.checked})}
                      />
                      <div className="w-11 h-6 rounded-full peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all"
                        style={{
                          background: formData.is_active 
                            ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                            : theme.borderColor
                        }}></div>
                    </label>
                    <span style={{ color: theme.textPrimary, fontWeight: 500 }}>
                      启用模型
                    </span>
                  </div>
                </div>
                
                <div className="flex gap-3 justify-end mt-8">
                  <CustomButton 
                    type="secondary"
                    onClick={() => setIsModelModalVisible(false)}
                    className="px-6"
                  >
                    取消
                  </CustomButton>
                  <CustomButton
                    type="primary"
                    htmlType="submit"
                    className="px-6 py-2 rounded-md font-medium text-white transition-all duration-300 hover:scale-105"
                    loading={loading.models}
                  >
                    创建模型
                  </CustomButton>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* 成功提示 */}
      {showSuccessToast && (
        <div className="fixed bottom-6 right-6 px-6 py-3 rounded-xl shadow-2xl z-50 animate-slide-up flex items-center gap-2"
          style={{
            background: 'linear-gradient(135deg, #00d2ff 0%, #3a47d5 100%)',
            color: 'white'
          }}>
          <span className="text-xl text-white animate-bounce"><FaCheck className="text-white" /></span>
          <span className="font-medium">操作成功！</span>
        </div>
      )}
      
    </div>
  );
};

export default AIModelManager;